package com.rabbit.client;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Channel02_queue_email {
    //队列1
    private  static  final  String QUEUE_EMAIL="queue_email";
    //队列2
    private  static  final  String QUEUE_SMS="queue_sms";
    //交换机
    private  static  final  String EXCHANGES_INFORM="exchanges_inform";

    public  static void main(String[] args){
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection=null;
        try {
            connection=connectionFactory.newConnection();
            Channel channel= connection.createChannel();

            //声明交换机
            channel.queueDeclare(QUEUE_EMAIL,true,false,false,null);


            //申明对列
            channel.exchangeDeclare(EXCHANGES_INFORM,BuiltinExchangeType.FANOUT);
            //绑定队列交换机
            channel.queueBind(QUEUE_EMAIL,EXCHANGES_INFORM,"");

            DefaultConsumer defaultConsumer =new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String Exchange = envelope.getExchange();
                    String message = new String(body,"UTF-8");
                    System.out.println(message);
                }
            };
            //监听队列
            channel.basicConsume(QUEUE_EMAIL,true,defaultConsumer);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
